﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Swagger;
using SXICE.Core.Infrastructure;
using SXICE.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SXICE.AdminAPI.Filters
{
    /// <summary>
    /// 异常全局过滤器
    /// </summary>
    public class ExceptionFilter : ExceptionFilterAttribute
    {
        private readonly ILog log;

        public ExceptionFilter(ILog log)
        {
            this.log = log;
        }

        public override void OnException(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                //定义返回信息

                ReturnResult res = new ReturnResult();
                res.ErrorCode = 500;
                res.ErrorMessage = "发生错误,请联系管理员";
                res.Success = false;

                //写入日志
                log.Error(context.Exception);

                context.Result = new ContentResult
                {
                    // 返回状态码设置为200，表示成功
                    StatusCode = StatusCodes.Status200OK,
                    // 设置返回格式
                    ContentType = "application/json;charset=utf-8",
                    Content = JsonConvert.SerializeObject(res)
                };
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;
        }
    }
}